<script setup>
import NavBack from "@/components/NavBack.vue";
import { reactive, ref, onBeforeUnmount } from "vue";
import { Toast } from "vant";
import { userLogin, userPhoneCode } from "@/api";
import { storage } from "@/assets/utils";
import { useStore } from "vuex";
import { useRoute, useRouter } from "vue-router";

const store = useStore(),
  route = useRoute(),
  router = useRouter();

// 初始化状态
let formIns = ref(null);
let state = reactive({
  phone: "",
  code: "",
  confirmLoading: false,
  send: {
    loading: false,
    disabled: false,
    text: "发送验证码",
  },
});

// 发送验证码
let autoTimer = null;
const clear = () => {
  clearInterval(autoTimer);
  state.send.disabled = false;
  state.send.loading = false;
  state.send.text = "发送验证码";
  state.confirmLoading = false;
  formIns.value.resetValidation();
};
onBeforeUnmount(clear);
const sendHandle = async () => {
  try {
    await formIns.value.validate("phone");
    state.send.disabled = true;
    state.send.loading = true;
    let { code } = await userPhoneCode(state.phone);
    if (+code === 0) {
      state.send.loading = false;
      state.send.text = "30s后重发";
      let num = 30;
      autoTimer = setInterval(() => {
        num--;
        state.send.text = `${num}s后重发`;
        if (num <= 0) {
          state.send.disabled = false;
          state.send.text = "发送验证码";
          clearInterval(autoTimer);
        }
      }, 1000);
      return;
    }
    Toast.fail("发送失败");
  } catch (_) {}
  state.send.disabled = false;
  state.send.loading = false;
};

// 登录提交
const submitHandle = async () => {
  try {
    state.confirmLoading = true;
    let { code, token } = await userLogin(state.phone, state.code);
    if (+code === 0) {
      // 登录成功:存储TK、获取登录者信息、提示、跳转
      storage.set("tk", token);
      await store.dispatch("queryProfileAsync");
      Toast.success("登录成功");
      router.push("/person");
    } else {
      Toast.fail("登录失败");
    }
  } catch (_) {}
  state.confirmLoading = false;
};
</script>

<template>
  <nav-back title="登录/注册" />
  <van-form @submit="submitHandle" ref="formIns">
    <van-cell-group inset>
      <van-field
        center
        label="手机号"
        label-width="50px"
        name="phone"
        v-model.trim="state.phone"
        :rules="[
          {
            pattern: /^(?:(?:\+|00)86)?1\d{10}$/,
            message: '手机号输入有误',
          },
        ]"
      >
        <template #button>
          <van-button
            class="form-btn"
            size="small"
            type="primary"
            loading-text="处理中"
            :loading="state.send.loading"
            :disabled="state.send.disabled"
            @click="sendHandle"
          >
            {{ state.send.text }}
          </van-button>
        </template>
      </van-field>

      <van-field
        label="验证码"
        label-width="50px"
        name="code"
        v-model.trim="state.code"
        :rules="[
          {
            pattern: /^\d{6}$/,
            message: '验证码输入有误',
          },
        ]"
      />
    </van-cell-group>

    <div style="margin: 20px 40px">
      <van-button
        round
        block
        type="primary"
        native-type="submit"
        loading-text="正在处理中..."
        :loading="state.confirmLoading"
      >
        立即登录/注册
      </van-button>
    </div>
  </van-form>
</template>

<style lang="less" scoped>
.van-form {
  margin-top: 30px;

  .form-btn {
    width: 78px;
  }
}
</style>